<template>
  <div>
    <j-modal
      id="ReModel"
      title="地图选点"
      width="800px"
      height="800px"
      :visible="visible"
      switchFullscreen
      @ok="ok"
      :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <a-form layout="inline">
        <a-form-item label="搜索位置">
          <a-input id="searchAddres" v-model="searchAddresKeywords" placeholder="请输入地址" />
        </a-form-item>
        <a-form-item label="当前位置">
          <a-input :addon-before="beforAddress" v-model="afterAddress" :disabled="true" />
        </a-form-item>
      </a-form>
      <baidu-map
        id="test"
        :scroll-wheel-zoom="true"
        class="map"
        :center="location"
        :zoom="zoom"
        @ready="handler"
        @load="load"
      >
        <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
      </baidu-map>
    </j-modal>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    //这里存放数据
    return {
      searchAddresKeywords: '',
      location: '{ lng: 134.5680442, lat: 48.26848028 }',
      addressInfo: {
        // 地址信息
        longitude: '', // 经度
        latitude: '', // 纬度
      },
      beforAddress: '',
      afterAddress: '',
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    visible(newValue, oldValue) {
      console.log(newValue)
    },
  },
  //方法集合
  methods: {
    ok() {
      this.$emit('ok', this.addressInfo)
    },

    getNowLocation() {
      console.log(1)
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(this.locationSuccess, this.locationError, {
          // 指示浏览器获取高精度的位置，默认为false
          enableHighAccuracy: true,
          // 指定获取地理位置的超时时间，默认不限时，单位为毫秒
          timeout: 5000,
          // 最长有效期，在重复获取地理位置时，此参数指定多久再次获取位置。
          maximumAge: 3000,
        })
      } else {
        alert('浏览器不支持Html5来获取地理位置信息')
      }
    },
    handleCancel() {
      this.afterAddress = ''
      this.beforAddress = ''
      this.searchAddresKeywords = ''
      this.$emit('close')
    },
    handler({ BMap, map }) {
      this.$nextTick(function () {
        this.getNowLocation()
        this.zoom = 15
        let that = this

        /** 点击地图创建坐标事件Start */
        // 添加地图点击事件
        map.addEventListener('click', function (e) {
          var clickpt = e.point // 点击的坐标
          map.clearOverlays() // 移除地图上的标注
          var marker = new BMap.Marker(new BMap.Point(clickpt.lng, clickpt.lat)) // 创建标注

          map.addOverlay(marker) // 将标注添加到地图中
          // 逆地址解析
          that.geocAddress(clickpt)
        })
        /** 点击地图创建坐标事件End */

        /** 搜索地址Start */
        //建立一个自动完成的对象
        var ac = new BMap.Autocomplete({
          input: 'searchAddres',
          location: map,
        })
        console.log(ac)
        // 鼠标点击下拉列表后的事件
        ac.addEventListener('onconfirm', function (e) {
          console.log(e)
          map.clearOverlays() // 移除地图上的标注
          var local = new BMap.LocalSearch(map, {
            //智能搜索
            onSearchComplete: function (results) {
              let poi = results.getPoi(0) //获取第一个智能搜索的结果
              var searchpt = poi.point // 获取坐标
              map.centerAndZoom(searchpt, 16)
              map.addOverlay(new BMap.Marker(searchpt)) //添加标注
              that.geocAddress(searchpt) // 逆地址解析
            },
          })
          // 搜索词
          var searchValue = e.item.value
          local.search(
            searchValue.province + searchValue.city + searchValue.district + searchValue.street + searchValue.business
          )
        })
      })

      /** 搜索地址End */
    },
    //获取当前位置回调
    locationSuccess(point, AddressComponent, marker) {
      this.location.lat = point.coords.latitude
      this.location.lng = point.coords.longitude
      console.log(this.location)
    },
    locationError(error) {
      switch (error.code) {
        case error.TIMEOUT:
          alert('连接超时，请重试')
          break
        case error.POSITION_UNAVAILABLE:
          alert('非常抱歉，我们暂时无法为您所在的星球提供位置服务')
          break
        case error.PERMISSION_DENIED:
          alert('您拒绝了使用位置共享服务，查询已取消')
          break
        default:
          alert('发生未知错误!')
          break
      }
    },

    /** 逆向解析地址 point */
    geocAddress(point) {
      let that = this
      var geoc = new BMap.Geocoder()
      geoc.getLocation(point, function (geocInfo) {
        console.log(geocInfo)
        // 设置基本信息
        var addressInfo = geocInfo.addressComponents
        that.addressInfo.longitude = point.lng
        that.addressInfo.latitude = point.lat
        that.addressInfo.province = addressInfo.province
        that.addressInfo.city = addressInfo.city
        that.addressInfo.district = addressInfo.district
        let address = addressInfo.street + addressInfo.streetNumber

        that.beforAddress = addressInfo.province + addressInfo.city + addressInfo.district + addressInfo.street
        that.afterAddress = address
        console.log(that.afterAddress)
        if (geocInfo.surroundingPois.length > 0) {
          address = address + geocInfo.surroundingPois[0].title
        }
        that.addressInfo.address = address
      })
      console.log(this.addressInfo.city)
    },
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {},
  //声明周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style >
#test {
  height: 400px;
  width: 700px;
  margin-left: 20px;
  background-color: rgb(192, 228, 127);
}
.bm-view {
  width: 80%;
  height: 80%;
}
.tangram-suggestion-main {
  z-index: 999999;
}
</style>